package com.yikes.srb.service.impl;

import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yikes.srb.common.result.PageResult;
import com.yikes.srb.common.utils.object.BeanUtils;
import com.yikes.srb.constant.hfb.FormHelper;
import com.yikes.srb.constant.hfb.HfbConst;
import com.yikes.srb.constant.hfb.RequestHelper;
import com.yikes.srb.leadingModle.form.userBind.UserBindAddForm;
import com.yikes.srb.leadingModle.form.userBind.UserBindEditForm;
import com.yikes.srb.leadingModle.form.userBind.UserBindForm;
import com.yikes.srb.leadingModle.form.userBind.UserBindQuery;
import com.yikes.srb.leadingModle.vo.UserBindVO;
import com.yikes.srb.mapper.UserInfoMapper;
import com.yikes.srb.pojo.entity.UserBind;
import com.yikes.srb.mapper.UserBindMapper;
import com.yikes.srb.pojo.entity.UserInfo;
import com.yikes.srb.pojo.enums.ServiceWorkCodeEnum;
import com.yikes.srb.pojo.enums.UserBindEnum;
import com.yikes.srb.service.UserBindService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yikes.srb.web.utils.As;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 * 用户绑定表 服务实现类
 * </p>
 *
 * @author guanrong.yin
 * @since 2024-12-03
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class UserBindServiceImpl extends ServiceImpl<UserBindMapper, UserBind> implements UserBindService {

    private final UserInfoMapper userInfoMapper;

    @Override
    public PageResult<UserBindVO> listPage(UserBindQuery query) {

        Page<UserBind> page = lambdaQuery()
                .eq(ObjectUtil.isNotNull(query.getUserId()), UserBind::getUserId, query.getUserId())
                .like(StrUtil.isNotBlank(query.getName()), UserBind::getName, query.getName())
                .like(StrUtil.isNotBlank(query.getIdCard()), UserBind::getIdCard, query.getIdCard())
                .like(StrUtil.isNotBlank(query.getBankNo()), UserBind::getBankNo, query.getBankNo())
                .like(StrUtil.isNotBlank(query.getBankType()), UserBind::getBankType, query.getBankType())
                .like(StrUtil.isNotBlank(query.getMobile()), UserBind::getMobile, query.getMobile())
                .like(StrUtil.isNotBlank(query.getBindCode()), UserBind::getBindCode, query.getBindCode())
                .eq(ObjectUtil.isNotNull(query.getStatus()), UserBind::getStatus, query.getStatus())
                .page(Page.of(query.getPageNum(), query.getPageSize()));

        List<UserBindVO> bean = BeanUtils.toBean(page.getRecords(), UserBindVO.class);
        return PageResult.build(page.getTotal(), page.getPages(), bean);
    }

    @Override
    public UserBindVO infoId(Long id) {

        UserBind userBind = getById(id);
        UserBindVO bean = BeanUtils.toBean(userBind, UserBindVO.class);
        return bean;
    }

    @Override
    public void create(UserBindAddForm form) {

        UserBind bean = BeanUtils.toBean(form, UserBind.class);
        save(bean);

    }

    @Override
    public void edit(UserBindEditForm form) {

        UserBind bean = BeanUtils.toBean(form, UserBind.class);
        updateById(bean);
    }

    @Override
    public void del(Long id) {
        baseMapper.deleteById(id);
    }

    @Override
    public String commitBindUser(UserBindForm form, Long userId) {

        //查询身份证号码是否绑定
        UserBind userBind = lambdaQuery().eq(UserBind::getIdCard, form.getIdCard()).ne(UserBind::getUserId, userId).one();
        As.isNull(userBind, ServiceWorkCodeEnum.USER_BIND_IDCARD_EXIST_ERROR);

        //查询用户绑定信息
        userBind = baseMapper.selectOne(lambdaQuery().eq(UserBind::getUserId, userId));

        //判断是否有绑定记录
        if (userBind == null) {
            //如果未创建绑定记录，则创建一条记录
            userBind = new UserBind();
            BeanUtils.copyProperties(form, userBind);
            userBind.setUserId(userId);
            userBind.setStatus(UserBindEnum.NO_BIND.getStatus());
            baseMapper.insert(userBind);
        } else {
            //曾经跳转到托管平台，但是未操作完成，此时将用户最新填写的数据同步到userBind对象
            BeanUtils.copyProperties(form, userBind);
            baseMapper.updateById(userBind);
        }

        Map<String, Object> paramMap = new HashMap<>();
        paramMap.put("agentId", HfbConst.AGENT_ID);
        paramMap.put("agentUserId", userId);
        paramMap.put("idCard", form.getIdCard());
        paramMap.put("personalName", form.getName());
        paramMap.put("bankType", form.getBankType());
        paramMap.put("bankNo", form.getBankNo());
        paramMap.put("mobile", form.getMobile());
        paramMap.put("returnUrl", HfbConst.USERBIND_RETURN_URL);
        paramMap.put("notifyUrl", HfbConst.USERBIND_NOTIFY_URL);
        paramMap.put("timestamp", RequestHelper.getTimestamp());
        paramMap.put("sign", RequestHelper.getSign(paramMap));

        //构建充值自动提交表单
        return FormHelper.buildForm(HfbConst.USERBIND_URL, paramMap);

    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void notify(Map<String, Object> paramMap) {

        String bindCode = (String)paramMap.get("bindCode");
        //会员id
        String agentUserId = (String)paramMap.get("agentUserId");

        //根据user_id查询user_bind记录
        //更新用户绑定表
        UserBind userBind = baseMapper.selectOne(lambdaQuery().eq(UserBind::getUserId, agentUserId));
        userBind.setBindCode(bindCode);
        userBind.setStatus(UserBindEnum.BIND_OK.getStatus());
        baseMapper.updateById(userBind);

        //更新用户表
        UserInfo userInfo = userInfoMapper.selectById(agentUserId);
        userInfo.setBindCode(bindCode);
        userInfo.setName(userBind.getName());
        userInfo.setIdCard(userBind.getIdCard());
        userInfo.setBindStatus(UserBindEnum.BIND_OK.getStatus());
        userInfoMapper.updateById(userInfo);
    }

    @Override
    public String getBindCodeByUserId(Long investUserId) {

        UserBind userBind = lambdaQuery().eq(UserBind::getUserId, investUserId).one();

        return userBind.getBindCode();
    }
}
